package array;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

public class DynamicArray implements Iterable<Integer> {
    private int[] array = {};
    private int size = 0;
    private int capacity = 10;

    public boolean append(int target) {
        return insert(size, target);
    }

    public boolean insert(int index, int target) {
        checkAndInit(index);
        if (index == size) {
            array[size++] = target;
            return true;
        }
        for (int i = size; i >= index; i--) {
            array[i + 1] = array[i];
        }
        array[index] = target;
        size++;
        return true;
    }

    public int get(int index) {
        return array[index];
    }

    private void checkAndInit(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException(String.format("给出索引[%d]越界",index));
        }
        if (size == 0) {
            array = new int[capacity];
        } else if (size == capacity) {
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            for (int i = 0; i < size; i++) {
                newArray[i] = array[i];
            }
            array = newArray;
        }
    }

    // foreach循环 函数式接口
    public void foreach(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }

    // iterator 迭代器 需要实现 iterable接口
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0; // 初始化指针指向0

            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }
        };
    }

    // stream流循环
    public IntStream stream() {// param 数组 起始索引 长度
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    public int remove(int index){
        int value = get(index);
        for(int i=index;i<size;i++){
            array[i] = array[i+1];
        }
        size--;
        return value;
    }

}
